import { Button, Table } from 'antd'
import Input from 'antd/lib/input/Input'
import { useCallback, useEffect, useState } from 'react'
import './App.css'
let keyrow=11

function App() {
  const [listData, setListData] = useState([])
  const [tableKey, setTableKey] = useState(0)
  const [tableColumns, setTableColumns] = useState(0)

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
      render: (txt, record, idx) => {
        return <Input value={txt} onChange={e => onChangeTxt(e, record, 'age', idx)}></Input>
      }
    }
  ]

  const onChangeTxt = useCallback((e, record, key, idx) => {
    console.log(' listData -->-30', listData)
    // record[key] = e.target.value

    let _data = listData
    if(_data[idx]){
      _data[idx][key] = e.target.value
    }
    setListData([..._data])
  },[listData])

  useEffect(() => {
    setListData([
      { name: '章三', age: 4, key: 1,test1:'wii' },
      { name: '里斯', age: 3, key: 2,test1:'wii' }
    ])
    setTableColumns(columns)
  }, [])
  const onSet = useCallback(() => {
    let _data = listData
    if(_data[1]){
      _data[1].name = '王二-------'
      _data[1].age = 10000
    }
    
    setListData([..._data])
    // let _columns = [{
    //   title: '测试1',
    //   dataIndex: 'test1',
    //   key: 'test1'
    // },...columns]
    columns.unshift({
      title: '测试1',
      dataIndex: 'test1',
      key: 'test1'
    })
    setTableColumns(columns)
    let _key = tableKey + 1
    setTableKey(_key)
  }, [listData,columns])
  const onAdd = useCallback(() => {
    let _data = listData
    keyrow=keyrow+1
    console.log(' keyrow -->-59', keyrow)
    _data.push({ name: '玄虚', age: 14, key: keyrow,test1:'2234' })
    setListData([..._data])
    // let _key = tableKey + 1
    // setTableKey(_key)
  }, [listData])

  return (
    <div className='App'>
      <Button onClick={onSet}>设置columns</Button> &nbsp;
      <Button onClick={onAdd}>添加</Button> 
      {listData.map(item => (
        <p key={item.name}>
          {item.name}-{item.age}
        </p>
      ))}
      {tableKey}
      <Table key={tableKey} dataSource={listData} columns={tableColumns} />;
    </div>
  )
}

export default App
